package com.fan.client;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

import java.util.concurrent.atomic.AtomicBoolean;

public class PropertySourcesProcessor implements BeanFactoryPostProcessor, EnvironmentAware, ApplicationContextAware {
    private static final String PROPERTY_SOURCE_NAME = "PropertySources";
    private static final AtomicBoolean PROPERTY_SOURCES_INITIALIZED = new AtomicBoolean(false);

    private ConfigurableEnvironment environment;
    private ConfigContext configContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        if (!PROPERTY_SOURCES_INITIALIZED.compareAndSet(false, true)) {
            // already initialized
            return;
        }
        initializePropertySources();
    }

    protected void initializePropertySources() {
        String[] activeProfiles = environment.getActiveProfiles();
        String configUrl = environment.getProperty("config.url");
        String appName = environment.getProperty("config.appName");
        CompositePropertySource composite = new CompositePropertySource(PROPERTY_SOURCE_NAME);
        ConfigManager configManager = ConfigManager.INSTANCE;
        PropertyConfig propertyConfig = configManager.getPropertyConfig();
        propertyConfig.setProfile(activeProfiles[0]);
        propertyConfig.setAppName(appName);
        propertyConfig.setConfigUrl(configUrl);
        configContext.getProperty();
        composite.addPropertySource(new ConfigPropertySource("property", propertyConfig));
        environment.getPropertySources().addFirst(composite);

    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (ConfigurableEnvironment) environment;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ConfigContext bean = applicationContext.getBean(ConfigContext.class);
        this.configContext = bean;
    }
}
